#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <dirent.h>

#define DIR_PATH    "/mnt/myusb/video"
#define CMD_PID     "pgrep v4l2"
#define myinfo(format, args...)           \
    do{                                   \
        printf("\033[1;42m");             \
        printf("[makevideo] ");           \
        printf(format, ##args);           \
        printf("\033[0m\n");              \
    }while(0)
#define myerror(format, args...)          \
    do{                                   \
        printf("\033[1;41m");             \
        printf("[makevideo] ");           \
        printf(format, ##args);           \
        printf("\033[0m\n");              \
    }while(0)

//获取进程号
int get_pid(void)
{
    FILE *fp;
    char buffer[20];
    int pid;
    fp = popen(CMD_PID, "r");  //管道
    if(fgets(buffer, sizeof(buffer), fp) == NULL)
    {
        myerror("No matching process found.\n");
        exit(-1);
    }
    else
    {
        pid = atoi(buffer);
    }
    pclose(fp);
    return pid;
}

//使用 ffmpeg 转换图片为视频
void make_video(void)
{
    time_t now = time(NULL);        //当前时间戳		 
    struct tm* local_time = localtime(&now);
    char time_str[20], str[130]; 
    strftime(time_str, sizeof(time_str), "%Y%m%d%H%M%S", local_time);
    sprintf(str,"ffmpeg -framerate 10 -pattern_type glob -i '*.jpg' -c:v libx264 -pix_fmt yuv420p -color_range jpeg -r 10 %s.mp4", time_str);
    system(str);
}
//删除所有图片
void delete_photos(void)
{    
    DIR *dir = opendir(DIR_PATH);
    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL)
    {
        int len = strlen(entry->d_name);
        if (strcmp(entry->d_name + len - 4, ".jpg") == 0)
        {
            char file_path[100];
            snprintf(file_path, sizeof(file_path), "%s/%s", DIR_PATH, entry->d_name);
            unlink(file_path);
            printf("Deleted file: %s\n", file_path);
        }
    }
    closedir(dir);
}

void sig_handler(int sig)
{ 
    if(sig == SIGUSR2)
    {   
        int pid = get_pid();
        myinfo("QT pid = %d",pid);
        make_video();
        myinfo("Make video success!"); 
        delete_photos();
        myinfo("Delete all photos!"); 
        if (kill(pid, SIGUSR1) != 0)
        {
            myerror("Kill SIGUSR1 to QT error!");
            exit(-1);
        }
        myinfo("Kill SIGUSR1 to QT success!");
    }
}

int main()
{
    signal(SIGUSR2, sig_handler);
    if(chdir(DIR_PATH) != 0)
    {
        myerror("Failed to change directory!");
        exit(-1);
    }
    while(1)
    {
        myinfo("Waiting SIGUSR2 from QT...");    
        pause();
    }    
    return 0;
}
